<?php 
namespace app\common\model;
use think\Model;
use app\common\model\AdminLog;
/**
 * @Author: YeMiao
 * @Date:   2017-07-31 11:23:22
 * @Last Modified by:   YeMiao
 * @Last Modified time: 2017-08-11 10:04:48
 */
class Category extends Model{
	protected $resultSetType = 'collection';

	// 获取全部数据
	public function get_list(){
		$category = $this->select()->toArray();
		return $category;		
	}
	// 获取一级分类的数据
	public function get_f_list(){
		$category = $this->where('fid','0')->select()->toArray();
		return $category;
	}
	// 根据id找数据
	public function find_id($data){
		if(isset($data['id'])){
			$category = $this->where('id',$data['id'])->find()->toArray();
		}else{
			$category = $this->where('id',$data)->find()->toArray();
		}		
		return $category;
	}
	// 添加数据
	public function add_category($data){
		try {
			$category = $this->save($data);
		} catch (\Exception $e) {
			return 0;
		}
		if($data['fid'] == 0){
			$str = '一级分类';
		}else{
			$find = $this->find_id($data['fid']);
			$str = $find['catename'];
		}
		$log = new AdminLog();
		$log->add_log('添加栏目,'.$str.'->'.$data['catename']);	
		return $category;
	}
	// 删除数据
	public function del_category($data){
		$find = $this->get($data['id']);
		if($find['fid'] == 0){
			try {
				$str = '一级分类';
				$this->where('fid',$find['id'])->delete();		
			} catch (\Exception $e) {
				return 0;
			}
		}else{
			try {
				$f_find = $this->find_id($find['fid']);
				$str = $f_find['catename'];	
			} catch (\Exception $e) {
				return 0;
			}			
		}		
		$log = new AdminLog();
		$log->add_log('删除栏目,'.$str.'->'.$find['catename']);
		try {
			$category = $this->destroy($data['id']);			
		} catch (\Exception $e) {
			return 0;
		}	
		return $category;
	}
	// 更新数据
	public function update_category($data){
		$find = $this->find_id($data['id']);
		$q_f_find = $this->find_id($find['fid']);
		$h_f_find = $this->find_id($data['fid']);		
		$log = new AdminLog();
		$log->add_log('修改'.$find['catename'].'栏目,父类:"'.$q_f_find['catename'].'"->"'.$h_f_find['catename'].'"名称:"'.$find['catename'].'"->"'.$data['catename'].'",排序:"'.$find['order'].'"->"'.$data['order'].'"');
		try {
			$category = $this->update($data);
		} catch (\Exception $e) {
			return 0;
		}		
		return 1;
	}
	// 更新状态
	public function update_show_category($data){
		if($data['show'] == 1){
			$data['show'] = 0;
			$str = '不显示';
		}else{
			$data['show'] = 1;
			$str = '显示';
		}
		$find = $this->find_id($data['id']);
		$log = new AdminLog();
		$log->add_log('修改'.$find['catename'].'栏目:导航'.$str);
		try {
			$category = $this->update($data);
		} catch (\Exception $e) {
			return 0;
		}		
		return 1;
	}
}

 ?>